package com.ftqh.security.user.controller;

import com.ftqh.core.web.controller.AbstractController;
import com.ftqh.security.service.SecurityService;
import com.ftqh.security.user.domain.User;
import com.ftqh.security.user.service.UserService;
import com.ftqh.security.user.service.UserServiceImpl;
import com.ftqh.security.user.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2016/12/27
 * \* Time: 15:05
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@Controller
@SessionAttributes("authorizationRequest")
public class LoginController extends AbstractController<User, UserServiceImpl,Integer>{

    @Autowired
    private UserService userService;
    @Autowired
    private SecurityService securityService;
    @Autowired
    private UserValidator userValidator;

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView register() {
        ModelAndView model = getModelAndViewInstance("register");
        model.addObject("userForm", createDomain());
        return model;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView register(@ModelAttribute("userForm") User userForm, BindingResult bindingResult) {
        userValidator.validate(userForm, bindingResult);
        ModelAndView model = getModelAndViewInstance("register");
        if (bindingResult.hasErrors()) {
            System.out.println("###########"+bindingResult.getAllErrors());

            return model;
        }
        userService.save(userForm);
        System.out.println("#########"+userForm.getPassword());
        securityService.autologin(userForm.getUsername(),userForm.getPasswordConfirm());
        model.setViewName(getPagePrex()+"welcome");
        return model;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(String error, String logout) {
        ModelAndView model = getModelAndViewInstance("login");
        if (error != null)
            System.out.println(error);
            model.addObject("error", "Your username and password is invalid.");

        if (logout != null)
            model.addObject("message", "You have been logged out successfully.");

        return model;
    }

    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        HttpRequestResponseHolder responseHolder = new HttpRequestResponseHolder(request, response);
        securityService.autologin(request.getParameter("username"),request.getParameter("password"));
        ModelAndView model = getModelAndViewInstance("welcome");
        model.setViewName(getPagePrex()+"welcome");
        return model;
    }
    @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
    public String welcome(Model model) {
        return "welcome";
    }
    @Override
    protected String getPagePrex() {
        return "";
    }

    @Override
    protected User createDomain() {
        return new User();
    }

    @Override
    protected void setAttributes(ModelAndView model, User domain) {

    }
    /**
     * Generate an authorization parameter map from the session's token request
     * @param defaultSavedRequest the default saved request from the session
     * @return a map of parameters containing the OAuth2 request details
     */
    private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
        Map<String, String> authParams = new HashMap<>();

        authParams.put(OAuth2Utils.CLIENT_ID,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

        authParams.put(OAuth2Utils.REDIRECT_URI,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

        if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
            authParams.put(OAuth2Utils.STATE,
                    defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
        }

        authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
        authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
        authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
        return authParams;
    }
}
